<template>
  <div>
    <el-header style="display: flex; align-items: center; justify-content: flex-start; padding-left: 5px; margin-top:5px; margin-bottom:5px">
  <i class="el-icon-location-information" style="font-size:20px; margin-right:5px">
    当前位置：用户与权限管理
  </i>
</el-header>

<div class="search" style="display: flex; align-items: center; justify-content: space-between;">
  <div style="display: flex; align-items: center;">
    <el-select v-model="selectedField"  style="width: 150px; margin-right: 10px;">
      <el-option label="用户编号" value="field1"></el-option>
      <el-option label="用户姓名" value="field2"></el-option>
      <el-option label="从事岗位" value="field3"></el-option>
      <el-option label="工段" value="field4"></el-option>
      <el-option label="班组" value="field5"></el-option>
      <el-option label="工位" value="field6"></el-option>
      <el-option label="权限等级" value="field7"></el-option>
      <el-option label="技能等级" value="field8"></el-option>
    </el-select>
    <input type="text" v-model="searchKeyword" placeholder="输入关键词搜索" style="width: 200px;">
    <button @click="search">
      <i class="el-icon-search"></i>
    </button>
  </div>
  <div style="display: flex; align-items: center;">
    <button @click="showAddModal" style="margin-left: 50px;">新增记录</button>
    <button @click="fetchData" style="margin-left: 50px;">加载数据库内容</button>
    <button @click="uploadData" style="margin-left: 50px;">上传数据</button>
  </div>
</div>


    <div class="table-container">
      <table class="custom-table">
        <thead>
          <tr>
            <th>序号</th>
            <th>用户编号</th>
            <th>用户姓名</th>
            <th>从事岗位</th>
            <th>工段</th>
            <th>班组</th>
            <th>工位</th>
            <th>权限等级</th>
            <th>技能等级</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in currentData" :key="item.field1">
            <td>{{ index + 1 + (currentPage - 1) * userItemsPerPage }}</td>
            <td>{{ item.field1 }}</td>
            <td>{{ item.field2 }}</td>
            <td>{{ item.field3 }}</td>
            <td>{{ item.field4 }}</td>
            <td>{{ item.field5 }}</td>
            <td>{{ item.field6 }}</td>
            <td>{{ item.field7 }}</td>
            <td>{{ item.field8 }}</td>
            <td>
              <button @click="editItem(index)">编辑</button>
              <button @click="deleteItem(index)">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 编辑表单 -->
    <div v-if="isEditing">
      <input type="text" v-model="editedItem.field1">
      <input type="text" v-model="editedItem.field2">
      <input type="text" v-model="editedItem.field3">
      <input type="text" v-model="editedItem.field4">
      <input type="text" v-model="editedItem.field5">
      <input type="text" v-model="editedItem.field6">
      <input type="text" v-model="editedItem.field7">
      <input type="text" v-model="editedItem.field8">
      <button @click="confirmEdit">确认</button>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="userItemsPerPage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.length">
      </el-pagination>
    </div>

    <!-- 新增记录模态框 -->
    <div v-if="showAddModalFlag" class="modal">
      <div class="modal-content">
        <span class="close" @click="closeAddModal">&times;</span>
        <div class="modal-body">
          <input type="text" v-model="newItem.field1" placeholder="用户编号">
          <input type="text" v-model="newItem.field2" placeholder="用户姓名">
          <input type="text" v-model="newItem.field3" placeholder="从事岗位">
          <input type="text" v-model="newItem.field4" placeholder="工段">
          <input type="text" v-model="newItem.field5" placeholder="班组">
          <input type="text" v-model="newItem.field6" placeholder="工位">
          <input type="text" v-model="newItem.field7" placeholder="权限等级">
          <input type="text" v-model="newItem.field8" placeholder="技能等级">
          <button @click="addNewItem">确认新增</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      currentPage: 1, // 当前页码
      userItemsPerPage: 10, // 每页显示条数
      filteredData: [],
      items: [],
      data: [],
      currentData: [],
      isEditing: false,
      editedItemIndex: null,
      editedItem: {
        field1: '',
        field2: '',
        field3: '',
        field4: '',
        field5: '',
        field6: '',
        field7: '',
        field8: ''
      },
      searchKeyword: '',
      selectedField: 'field1', // 设置初始选项
      showAddModalFlag: false,
      newItem: {
        field1: '',
        field2: '',
        field3: '',
        field4: '',
        field5: '',
        field6: '',
        field7: '',
        field8: ''
      }
    };
  },
   
  methods: {
    handleSizeChange(val) {
      this.userItemsPerPage = val; // 更新每页显示条数
      this.updateCurrentData(); // 调用方法更新当前数据
    },
    handleCurrentChange(val) {
      this.currentPage = val; // 更新当前页码
      this.updateCurrentData(); // 调用方法更新当前数据
    },
    updateCurrentData() {
      const start = (this.currentPage - 1) * this.userItemsPerPage;
      const end = start + this.userItemsPerPage;
      this.currentData = this.filteredData.slice(start, end); // 更新显示的数据
    },
    async uploadData() {
      try {
        const response = await axios.post('http://localhost:8000/api/user/addUser', this.data);
        console.log(response);
      } catch (error) {
        console.error('上传数据时发生错误:', error.message);
      }
    },
    async fetchData() {
try {
  const token = localStorage.getItem('token'); // 从 localStorage 获取 JWT token

  // 发送带有 Authorization 头的 GET 请求
  const response = await axios.get('http://localhost:8000/api/user/query', {
    headers: {
      'Authorization': `Bearer ${token}` // 使用 Bearer token 作为 Authorization 头
    },
    withCredentials: false // 启用跨域请求携带认证信息（可选，取决于后端是否需要）
  });

  if (response) {
    this.items = response.data;
    this.data = this.items.map(item => ({
      field1: item.number,
      field2: item.name,
      field3: item.post,
      field4: item.section,
      field5: item.workgroup,
      field6: item.position,
      field7: item.authority,
      field8: item.skills
    }));
    this.filteredData = this.data;
    this.updateCurrentData();
  } else {
    alert('Failed to fetch data.');
  }
} catch (error) {

  // 检查是否是权限不足（403）
  if (error.response && error.response.status === 403) {
    alert('没有权限访问该资源'); // 弹出权限不足的提示框
  } else {
    console.error('Error fetching data:', error);
    alert('数据获取失败，请稍后再试。');
  }
}

    },
    editItem(index) {
      this.editedItemIndex = index;
      this.editedItem = { ...this.currentData[index] };
      this.isEditing = true;
    },
    confirmEdit() {
      Object.assign(this.data[this.editedItemIndex + (this.currentPage - 1) * this.userItemsPerPage], this.editedItem);
      this.isEditing = false;
      this.editedItemIndex = null;
      this.editedItem = {};
    },
    deleteItem(index) {
      if (confirm("确认删除？")) {
        this.data.splice(index + (this.currentPage - 1) * this.userItemsPerPage, 1);
        this.updateCurrentData();
      }
    },
    showAddModal() {
      this.showAddModalFlag = true;
    },
    closeAddModal() {
      this.showAddModalFlag = false;
    },
    addNewItem() {
      if (Object.values(this.newItem).some(value => value.trim() === '')) {
        alert("请填写完整信息");
        return;
      }
      this.data.push({ ...this.newItem });
      this.showAddModalFlag = false;
      this.newItem = {
        field1: '',
        field2: '',
        field3: '',
        field4: '',
        field5: '',
        field6: '',
        field7: '',
        field8: ''
      };
      this.updateCurrentData();
    },
    search() {
      if (this.selectedField && this.searchKeyword) {
        this.filteredData = this.data.filter(item => item[this.selectedField].includes(this.searchKeyword));
      } else {
        this.filteredData = this.data;
      }
      this.currentPage = 1; // 搜索后重置页码
      this.updateCurrentData();
    }
  }
};
</script>








<style>
.table-container {
  text-align: center;
  margin: auto;
}
.custom-table {
  border-collapse: collapse;
  width: 80%;
  margin-bottom: 20px;
}
.custom-table th,
.custom-table td {
  border: 1px solid black;
  padding: 8px;
}
.pagination {
  margin-top: 20px;
}
.pagination button {
  margin-right: 5px;
}
.modal {
  display: flex; /* 使用 flex 布局 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  position: fixed;
  left: 50;
  top: 50;
  width: 200%;
  height: 200%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000; /* 确保模态框在最前面 */
}
.modal-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 5px;
  width: 200%;

  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  position: relative;
}
.close {
  position: absolute;
  right: 10px;
  top: 10px;
  color: #aaa;
  font-size: 28px;
  font-weight: bold;
  cursor: pointer;
}
.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
}
.modal-body input {
  display: block;
  margin: 10px 0;

  padding: 8px;
  box-sizing: border-box;
}
.modal-body button {
  display: block;
  width: 100%;
  padding: 10px;
  margin-top: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  cursor: pointer;
}
.modal-body button:hover {
  background-color: #45a049;
}

</style>
